<template>
  <div class="container">
    <div>
      <Logo />
      <h1 class="title">
        todoList实验
      </h1>
      <div class="links">
        <label>内容：</label>
        <a-input v-model="searchContent" />
        <a-button type="default" @click="toSearch">
          搜索
        </a-button>
        <a-button type="primary" @click="toAdd">
          添加任务
        </a-button>
      </div>
      <div class="todo-list">
        <table>
          <tbody>
            <tr>
              <th>id</th>
              <th>内容</th>
              <th>操作</th>
            </tr>
            <tr v-for="item of list" :key="item.id">
              <td>{{ item.id }}</td>
              <td>{{ item.content }}</td>
              <td>
                <a-button type="link" @click="toEdit(item.id)">
                  修改
                </a-button>
                <a-button type="link" @click="toDel(item.id)">
                  删除
                </a-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  asyncData (ctx) {
    const query = ctx.query
    if (query.content) {
      return ctx.$axios.get('/api/list?content=' + query.content).then(res => ({ list: res.data }))
    }
    return ctx.$axios.get('/api/list').then(res => ({ list: res.data }))
  },
  data () {
    return {
      searchContent: ''
    }
  },
  watch: {
    '$route' (to, from) {
      if (to.fullPath !== from.fullPath) {
        this.$nextTick(() => { // 不加this.$nextTick时，路由跳转后还是上一次的数据，所以需要加上
          this.search() // 需要执行的方法
        })
      }
    }
  },
  methods: {
    toAdd () {
      this.$router.push({ path: '/add' })
    },
    toDel (id) {
      this.$axios.$delete('/api/list/' + id).then((res) => {
        this.search()
      })
    },
    toEdit (id) {
      this.$router.push({ path: '/edit/' + id })
    },
    toSearch () {
      const searchContent = this.searchContent
      if (searchContent.length > 0) {
        this.$router.push({ path: '/', query: { content: searchContent } })
      } else {
        this.$router.push({ path: '/' })
      }
    },
    search () {
      if (this.$route.query.content && this.$route.query.content.length > 0) {
        this.$axios.get('/api/list?content=' + this.$route.query.content).then(res => (this.list = res.data))
      } else {
        this.$axios.get('/api/list').then(res => (this.list = res.data))
      }
    }
  }
}
</script>

<style>

</style>
